package api

import (
	"gitee.com/yangwencheng/vblog/apps/user"
	"gitee.com/yangwencheng/vblog/ioc"
	"gitee.com/yangwencheng/vblog/middleware"
	"github.com/gin-gonic/gin"
)

var _ ioc.ApiIocObj = &Handler{}

type Handler struct {
	srv user.Service
}

func (h *Handler) Name() string {
	return user.MODEL_NAME
}

func (h *Handler) Init() error {
	// 结构体之前的依赖关系 必须在Init 完成
	// 如果在init函数执行的话,很可能因为先后顺序导致空指针异常
	srv := ioc.App().GetController(user.MODEL_NAME)
	h.srv = srv.(user.Service)
	return nil
}

func NewHandler() *Handler {
	return &Handler{}
}

func (h *Handler) Register(r gin.IRouter) {
	r.Use(middleware.Cors())
	r.POST("/vblog/api/v1/user/login", h.Login)
	authorized := r.Group("")
	authorized.Use(middleware.Auth())
	{
		// 列表
		authorized.GET("/vblog/api/v1/users", h.QueryUser)
		// 创建
		authorized.POST("/vblog/api/v1/users", h.CreateUser)
		// 详情
		authorized.GET("/vblog/api/v1/users/:id", h.ShowUser)
		// 更新
		authorized.PUT("/vblog/api/v1/users/:id", h.UpdateUser)
		//删除
		authorized.DELETE("/vblog/api/v1/users/:id", h.DeleteUser)
		// info
		authorized.POST("/vblog/api/v1/user/info", h.Info)
	}

}

func init() {
	ioc.App().SetApi(NewHandler())
}
